#include "logger.h"
#include <log4cpp/Category.hh>
#include <log4cpp/OstreamAppender.hh>
#include <log4cpp/PatternLayout.hh>
#include <log4cpp/FileAppender.hh>
using namespace log4cpp;
//初始静态成员
Logger*Logger::_pInstance = nullptr;   
Category*Logger::_root = nullptr;

Logger::Logger(){
    //创建OstreamAppender (输出到控制台,和文件)
    OstreamAppender *osAppender = new OstreamAppender("console",&cout);
    FileAppender *fileAppender = new FileAppender("file","test.log");
   
    //创建PatternLayout(设置日志格式)
    PatternLayout* osPl = new PatternLayout();
    PatternLayout* filePl = new PatternLayout();

    osPl->setConversionPattern("%d %c [%p] %m%n");
    filePl->setConversionPattern("%d %c [%p] %m%n");

    osAppender->setLayout(osPl);
    fileAppender->setLayout(filePl);

    //获取根Category并配置
    _root = &Category::getRoot();
    _root->setAppender(osAppender);
    _root->setAppender(fileAppender);

    _root->setPriority(Priority::DEBUG);//调试级别
}

//清理log4cpp资源
Logger::~Logger(){
    Category::shutdown();
}

Logger* Logger::getInstance(){
    if(!_pInstance){
        _pInstance = new Logger();
    }
    return _pInstance;
}

void Logger::destroy(){
    if(_pInstance){
        delete _pInstance;
        _pInstance = nullptr;
    }
}

//日志输入实现
void Logger::warn(const char *file,int line,const char *func, const char *msg){
    _root->warn("[%s:%d (%s)] %s",file,line,func,msg);
}

void Logger::error(const char *file,int line,const char *func, const char *msg){
    _root->error("[%s:%d (%s)] %s",file,line,func,msg);
}

void Logger::debug(const char *file,int line,const char *func, const char *msg){
    _root->debug("[%s:%d (%s)] %s",file,line,func,msg);
}

void Logger::info(const char *file,int line,const char *func, const char *msg){
    _root->info("[%s:%d (%s)] %s",file,line,func,msg);
}
